package com.codegeek.project.slope.service.impl;

import com.codegeek.common.exception.CustomException;
import com.codegeek.common.utils.DateUtils;
import com.codegeek.common.utils.SecurityUtils;
import com.codegeek.common.utils.StringUtils;
import com.codegeek.framework.security.LoginUser;
import com.codegeek.project.slope.domain.SlopeDevice;
import com.codegeek.project.slope.domain.SlopeRepairRecord;
import com.codegeek.project.slope.domain.SlopeSensor;
import com.codegeek.project.slope.mapper.SlopeDeviceMapper;
import com.codegeek.project.slope.mapper.SlopeRepairRecordMapper;
import com.codegeek.project.slope.mapper.SlopeSensorMapper;
import com.codegeek.project.slope.service.ISlopeDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备Service业务层处理
 *
 * @author codegeek
 * @date 2020-02-17
 */
@Service
public class SlopeDeviceServiceImpl implements ISlopeDeviceService {
    @Autowired
    private SlopeDeviceMapper slopeDeviceMapper;

    @Autowired
    private SlopeSensorMapper slopeSensorMapper;

    @Autowired
    private SlopeRepairRecordMapper slopeRepairRecordMapper;

    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 查询设备
     *
     * @param deviceId 设备ID
     * @return 设备
     */
    @Override
    public SlopeDevice selectSlopeDeviceById(Long deviceId) {
        return slopeDeviceMapper.selectSlopeDeviceById(deviceId);
    }

    /**
     * 查询设备列表
     *
     * @param slopeDevice 设备
     * @return 设备
     */
    @Override
    public List<SlopeDevice> selectSlopeDeviceList(SlopeDevice slopeDevice) {
        return slopeDeviceMapper.selectSlopeDeviceList(slopeDevice);
    }

    @Override
    public List<SlopeDevice> selectSlopeOtherDeviceList(SlopeDevice slopeDevice) {
        return slopeDeviceMapper.selectSlopeOtherDeviceList(slopeDevice);
    }

    /**
     * 新增设备
     *
     * @param slopeDevice 设备
     * @return 结果
     */
    @Override
    public int insertSlopeDevice(SlopeDevice slopeDevice) {
        slopeDevice.setCreateTime(DateUtils.getNowDate());
        return slopeDeviceMapper.insertSlopeDevice(slopeDevice);
    }

    /**
     * 修改设备
     *
     * @param slopeDevice 设备
     * @return 结果
     */
    @Override
    public int updateSlopeDevice(SlopeDevice slopeDevice) {
        slopeDevice.setUpdateTime(DateUtils.getNowDate());
        return slopeDeviceMapper.updateSlopeDevice(slopeDevice);
    }

    /**
     * 批量删除设备
     *
     * @param deviceIds 需要删除的设备ID
     * @return 结果
     */
    @Override
    public int deleteSlopeDeviceByIds(Long[] deviceIds) {
        return slopeDeviceMapper.deleteSlopeDeviceByIds(deviceIds);
    }

    /**
     * 删除设备信息
     *
     * @param deviceId 设备ID
     * @return 结果
     */
    @Override
    public int deleteSlopeDeviceById(Long deviceId) {
        return slopeDeviceMapper.deleteSlopeDeviceById(deviceId);
    }

    @Override
    public List<Map<String, Object>> countSlopeDeviceByState() {
        return jdbcTemplate.queryForList(" select count(*) num,b.state from slope_sensor a left join slope_device b on a.device_id = b.device_id where b.is_valid=0 group by b.state");
    }

    @Override
    public int editDeviceState(Integer state, String devices) {
        String[] ids = devices.split(",");
        for (String id : ids) {
            SlopeDevice device = slopeDeviceMapper.selectSlopeDeviceById(Long.valueOf(id));
            Integer baseState = device.getState();
            if (state == 2 && baseState != 2) {
                SlopeRepairRecord repairRecord = new SlopeRepairRecord();
                repairRecord.setStartTime(new Date());
                SlopeSensor sensor = slopeSensorMapper.selectSlopeSensorByDeviceId(device.getDeviceId());
                repairRecord.setSensor(sensor);
                repairRecord.setDescription("人工操作维护");
                LoginUser loginUser = SecurityUtils.getLoginUser();
                repairRecord.setRespo(loginUser.getUsername());
                repairRecord.setRespoPhone(loginUser.getUser().getPhonenumber());
                repairRecord.setCreateBy(loginUser.getUsername());
                repairRecord.setCreateTime(new Date());
                slopeRepairRecordMapper.insertSlopeRepairRecord(repairRecord);
            } else if (state == 0 && baseState == 2) {
                SlopeRepairRecord repairRecord = new SlopeRepairRecord();
                SlopeSensor sensor = slopeSensorMapper.selectSlopeSensorByDeviceId(device.getDeviceId());
                repairRecord.setSensor(sensor);
                List<SlopeRepairRecord> list = slopeRepairRecordMapper.selectSlopeRepairRecordList(repairRecord);
                if (list.size() > 0) {
                    SlopeRepairRecord baseRecord = list.get(0);
                    baseRecord.setEndTime(DateUtils.getTime());
                    slopeRepairRecordMapper.updateSlopeRepairRecord(baseRecord);
                }
            }
        }
        StringBuilder sql = new StringBuilder(" update slope_device set state = '" + state + "' where device_id in (" + devices + ")");
        return jdbcTemplate.update(sql.toString());
    }

    /**
     * @param deviceList    设备列表
     * @param updateSupport 是否更新已有数据
     * @param operName      操作人
     * @return
     */
    @Override
    public String importDevice(List<SlopeDevice> deviceList, boolean updateSupport, String operName, List<Map<String, Object>> imeiList) {
        if (StringUtils.isNull(deviceList) || deviceList.size() == 0) {
            throw new CustomException("导入设备数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SlopeDevice device : deviceList) {
            Map<String, Object> map = new HashMap<>();
            map.put("imei", device.getImei());
            // 重复的时候不执行
            if (imeiList.contains(map)) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、设备 " + device.getDeviceName() + " 导入失败：";
                failureMsg.append("imei重复");
                continue;
            }
            try {
                // 验证是否存在这个设备
                SlopeDevice checkDevice = new SlopeDevice();
                checkDevice.setNumber(device.getNumber());
                List<SlopeDevice> flag = selectSlopeDeviceList(checkDevice);
                if (flag.size() == 0) {
                    this.insertSlopeDevice(device);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、设备 " + device.getDeviceName() + " 导入成功");
                } else if (updateSupport) {
                    device.setUpdateBy(operName);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、设备 " + device.getDeviceName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、设备 " + device.getDeviceName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、设备 " + device.getDeviceName() + " 导入失败：";
                failureMsg.append(msg);
//                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }


    @Override
    public SlopeDevice getDeviceByImei(String imei) {
        return slopeDeviceMapper.getDeviceByImei(imei);
    }

    @Override
    public List<Map<String, Object>> selectAllDeviceImei() {
        StringBuilder sql = new StringBuilder("SELECT imei FROM slope_device");
        return jdbcTemplate.queryForList(sql.toString());
    }

}
